//
//  ImagePreviewDownloader.m
//  Paparazzi
//
//  Created by Eric Williams on 11/18/10.
//  Copyright 2010 UCLA. All rights reserved.
//

#import "ImagePreviewDownloader.h" 
#import "Photo.h"

@implementation ImagePreviewDownloader

@synthesize delegate;

@synthesize myPhoto;
@synthesize myIndex;
@synthesize myData;
@synthesize myConnection;

- (void)startDownload: (NSString *) flickrFormatString
{
	// Create the data space to fill
    self.myData = [NSMutableData data];
	
	//case FlickrFetcherPhotoFormatSquare:    formatString = @"s"; break;
	//case FlickrFetcherPhotoFormatThumbnail: formatString = @"t"; break;
	//case FlickrFetcherPhotoFormatSmall:     formatString = @"m"; break;
	//case FlickrFetcherPhotoFormatMedium:    formatString = @"-"; break;
	//case FlickrFetcherPhotoFormatLarge:     formatString = @"b"; break;
	//case FlickrFetcherPhotoFormatOriginal:  formatString = @"o"; break;
	
	// alloc+init and start an NSURLConnection; release on completion/failure
	NSString *photoURLString = [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_%@.jpg", self.myPhoto.flickrFarm, self.myPhoto.flickrServer, self.myPhoto.flickrPhotoID, self.myPhoto.flickrSecret, flickrFormatString];
	NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:
                             [NSURLRequest requestWithURL:
                              [NSURL URLWithString:photoURLString]] delegate:self];
    self.myConnection = urlConnection;
    [urlConnection release];
}

- (void)cancelDownload
{
    [self.myConnection cancel];
    self.myConnection = nil;
    self.myData = nil;
}

- (void)dealloc
{
    [myIndex release];
    [myData release];
    [myConnection cancel];
    [myConnection release];
    
    [super dealloc];
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.myData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	// Clear the myData property to allow later attempts
    self.myData = nil;
    
    // Release the connection now that it's finished
    self.myConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{   
	// Clear data for future downloads
	NSData * finishedData = [NSData dataWithData:self.myData];
    self.myData = nil;
    
    // Release the connection now that it's finished
    self.myConnection = nil;
	
    // call our delegate and tell it that our icon is ready for display
    [delegate previewDownloadedWithData: finishedData forIndex: self.myIndex];
}

@end
